import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import apiService from '../utils/api.js'
import PlaylistForm from '../components/PlaylistForm.jsx'
import '../styles/pages.css'

function Library({ playSong, playPlaylist }) {
  const navigate = useNavigate()

  // 检查登录状态
  useEffect(() => {
    const checkLoginStatus = () => {
      const loginStatus = apiService.getLoginStatus()
      if (!loginStatus.isLoggedIn) {
        // 如果未登录，重定向到登录页面
        navigate('/login', { state: { from: '/library' } })
      }
    }
    
    checkLoginStatus()
  }, [navigate])
  
  // 状态管理
  const [playlists, setPlaylists] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [isPlaylistFormVisible, setIsPlaylistFormVisible] = useState(false)
  const [isEditingPlaylist, setIsEditingPlaylist] = useState(false)
  const [currentPlaylist, setCurrentPlaylist] = useState(null)
  
  // 从后端获取用户歌单
  const fetchUserPlaylists = async () => {
    setLoading(true)
    setError(null)
    try {
      const currentUser = apiService.getCurrentUser()
      const userId = currentUser?.id
      const response = await apiService.getUserPlaylists({ userId })
      console.log('获取歌单响应:', response)
      if (response.code === 200) {
        setPlaylists(response.data || [])
      } else {
        setError('获取歌单失败')
        // 使用模拟数据作为备选
        setPlaylists([
          { id: 1, name: '我喜欢的音乐', songCount: 56 },
          { id: 2, name: '跑步专属', songCount: 24 },
          { id: 3, name: '工作学习', songCount: 38 },
          { id: 4, name: '华语经典', songCount: 42 }
        ])
      }
    } catch (err) {
      console.error('获取歌单失败:', err)
      setError('网络错误，无法获取歌单')
      // 使用模拟数据作为备选
      setPlaylists([
        { id: 1, name: '我喜欢的音乐', songCount: 56 },
        { id: 2, name: '跑步专属', songCount: 24 },
        { id: 3, name: '工作学习', songCount: 38 },
        { id: 4, name: '华语经典', songCount: 42 }
      ])
    } finally {
      setLoading(false)
    }
  }
  
  // 组件挂载时获取歌单和最近播放
  useEffect(() => {
    fetchUserPlaylists()
    fetchRecentPlays()
  }, [])
  
  // 打开创建歌单表单
  const openCreatePlaylistForm = () => {
    setIsEditingPlaylist(false)
    setCurrentPlaylist(null)
    setIsPlaylistFormVisible(true)
  }
  
  // 打开编辑歌单表单
  const openEditPlaylistForm = (playlist) => {
    setIsEditingPlaylist(true)
    setCurrentPlaylist(playlist)
    setIsPlaylistFormVisible(true)
  }
  
  // 关闭歌单表单
  const closePlaylistForm = () => {
    setIsPlaylistFormVisible(false)
    setIsEditingPlaylist(false)
    setCurrentPlaylist(null)
  }
  
  // 处理歌单表单提交
  const handlePlaylistFormSubmit = async (formData) => {
    try {
      if (isEditingPlaylist && currentPlaylist) {
        // 更新歌单
        const response = await apiService.updatePlaylist(currentPlaylist.id, formData)
        if (response.code === 200) {
          // 更新歌单列表
          setPlaylists(playlists.map(playlist => 
            playlist.id === currentPlaylist.id ? response.data : playlist
          ))
          closePlaylistForm()
        } else {
          alert('编辑歌单失败: ' + response.message)
        }
      } else {
        // 创建新歌单
        const response = await apiService.createPlaylist(formData)
        if (response.code === 200) {
          // 添加新创建的歌单到列表
          setPlaylists([...playlists, response.data])
          closePlaylistForm()
        } else {
          alert('创建歌单失败: ' + response.message)
        }
      }
    } catch (err) {
      console.error(isEditingPlaylist ? '编辑歌单失败' : '创建歌单失败', err)
      alert('网络错误，无法' + (isEditingPlaylist ? '编辑' : '创建') + '歌单')
    }
  }
  
  // 最近播放歌曲状态
  const [recentPlays, setRecentPlays] = useState([])
  const [recentPlaysLoading, setRecentPlaysLoading] = useState(true)
  const [recentPlaysError, setRecentPlaysError] = useState(null)
  
  // 从后端获取最近播放歌曲
  const fetchRecentPlays = async () => {
    setRecentPlaysLoading(true)
    setRecentPlaysError(null)
    try {
      const response = await apiService.getRecentPlays()
      if (response.code === 200 && response.data && Array.isArray(response.data)) {
        setRecentPlays(response.data)
      } else {
        setRecentPlaysError('获取最近播放失败')
        // 使用模拟数据作为备选
        setRecentPlays([
          { id: 1, title: '晴天', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/100' },
          { id: 2, title: '海阔天空', artist: 'Beyond', album: '乐与怒', cover: 'https://via.placeholder.com/100' },
          { id: 3, title: '夜曲', artist: '周杰伦', album: '十一月的萧邦', cover: 'https://via.placeholder.com/100' },
          { id: 4, title: '南山南', artist: '马頔', album: '孤岛', cover: 'https://via.placeholder.com/100' },
          { id: 5, title: '小幸运', artist: '田馥甄', album: '我的少女时代', cover: 'https://via.placeholder.com/100' }
        ])
      }
    } catch (err) {
      console.error('获取最近播放失败:', err)
      setRecentPlaysError('网络错误，无法获取最近播放')
      // 使用模拟数据作为备选
      setRecentPlays([
        { id: 1, title: '晴天', artist: '周杰伦', album: '叶惠美', cover: 'https://via.placeholder.com/100' },
        { id: 2, title: '海阔天空', artist: 'Beyond', album: '乐与怒', cover: 'https://via.placeholder.com/100' },
        { id: 3, title: '夜曲', artist: '周杰伦', album: '十一月的萧邦', cover: 'https://via.placeholder.com/100' },
        { id: 4, title: '南山南', artist: '马頔', album: '孤岛', cover: 'https://via.placeholder.com/100' },
        { id: 5, title: '小幸运', artist: '田馥甄', album: '我的少女时代', cover: 'https://via.placeholder.com/100' }
      ])
    } finally {
      setRecentPlaysLoading(false)
    }
  }
  
  return (
    <div className="library-page">
      <div className="section-header">
          <h2>我的音乐</h2>
          <button className="btn-primary" onClick={openCreatePlaylistForm}>
            创建歌单
          </button>
        </div>
      
      {error && <div className="error-message">{error}</div>}
      
      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          {/* 我的歌单 */}
          <div className="section" style={{ marginBottom: '40px' }}>
            <h3>我的歌单</h3>
            <div className="playlist-list">
              {playlists.map((playlist) => (
                <div 
                  key={playlist.id} 
                  className="playlist-item"
                  onClick={(e) => {
                    // 点击编辑或播放按钮时不触发导航
                    if (!e.target.closest('.btn-edit') && !e.target.closest('.btn-play')) {
                      navigate(`/playlist/${playlist.id}`)
                    }
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  <div className="playlist-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M14 9V15M18 12H9M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#666" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </div>
                  <div className="playlist-info">
                    <h4 className="playlist-name">{playlist.name}</h4>
                    <p className="playlist-count">{playlist.songCount} 首歌曲</p>
                  </div>
                  <div className="playlist-actions">
                    <button className="btn-edit" onClick={() => openEditPlaylistForm(playlist)}>编辑</button>
                    <button className="btn-play" onClick={() => playPlaylist(playlist.id)}>播放</button>
                  </div>
                </div>
              ))}
            </div>
          </div>
          
          {/* 最近播放 */}
          <div className="section">
            <h3>最近播放</h3>
            
            {/* 错误信息显示 */}
            {recentPlaysError && (
              <div className="error-message">
                {recentPlaysError}
              </div>
            )}
            
            {/* 加载状态 */}
            {recentPlaysLoading ? (
              <div className="loading-container">
                <div className="loading-spinner"></div>
                <p>加载中...</p>
              </div>
            ) : (
              <div className="recent-play-list">
                {recentPlays.length > 0 ? (
                  recentPlays.map((row) => (
                    <div key={row.song.id} className="recent-play-item">
                      <img src={row.song.coverImageUrl} alt={`${row.song.title} - ${row.song.artist}`} />
                      <div className="song-info">
                        <h4 className="song-title">{row.song.title}</h4>
                        <p className="song-artist">{row.song.artist.name} · {row.song.album.title}</p>
                      </div>
                      <button className="btn-play-small" onClick={() => playSong(row.song)}>
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M8 5V19L19 12L8 5Z" fill="#1890ff"/>
                        </svg>
                      </button>
                    </div>
                  ))
                ) : (
                  <div className="empty-state">
                    <p>暂无最近播放记录</p>
                  </div>
                )}
              </div>
            )}
          </div>
        </>
      )}
      
      {/* 歌单表单组件（在我的音乐模块不显示官方推荐选项） */}
      <PlaylistForm
        isVisible={isPlaylistFormVisible}
        isEditing={isEditingPlaylist}
        initialData={currentPlaylist}
        onSubmit={handlePlaylistFormSubmit}
        onCancel={closePlaylistForm}
        showOfficialOption={false} // 我的音乐模块不显示官方推荐选项
      />
    </div>
  )
}

export default Library